package com.uestc.utils;

import java.io.*;
import java.util.List;

public class FileToBytesConverter {

    /**
     * 将文件列表转换为字节数组。
     *
     * @param files 文件列表
     * @return 所有文件内容的字节数组
     * @throws IOException 如果读取文件时发生错误
     */
    public static byte[] filesToBytes(List<File> files){
        // 计算所有文件的总大小
        long totalSize = files.stream().mapToLong(File::length).sum();
        byte[] bytes = new byte[(int) totalSize];

        int offset = 0;
        for (File file : files) {
            try (InputStream is = new FileInputStream(file)) {
                int bytesRead = is.read(bytes, offset, (int) file.length());
                if (bytesRead != file.length()) {
                    throw new IOException("未能完全读取文件: " + file.getName());
                }
                offset += bytesRead;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return bytes;
    }

    /**
     * 将单个文件转换为字节数组。
     *
     * @param filePath 文件路径
     * @return 文件内容的字节数组
     * @throws IOException 如果读取文件时发生错误
     */
    public static byte[] fileToBytes(String filePath){
        File file = new File(filePath);
        try (InputStream is = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            int bytesRead = is.read(bytes);
            if (bytesRead != file.length()) {
                throw new IOException("未能完全读取文件: " + filePath);
            }
            return bytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 示例：将文件路径转换为字节
        String singleFilePath = "path/to/your/file.txt";
        byte[] singleFileBytes = fileToBytes(singleFilePath);
        System.out.println("Single file bytes length: " + singleFileBytes.length);

        // 示例：将文件列表转换为字节
        List<File> fileList = List.of(new File("path/to/your/file1.txt"), new File("path/to/your/file2.txt"));
        byte[] filesBytes = filesToBytes(fileList);
        System.out.println("Files bytes length: " + filesBytes.length);
    }
}